<template>
  <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }">
    <a-row>
      <a-col :span="24" v-for="item in formOptions" :key="item.key">
        <a-form-item :label="item.nameZh" :name="item.key" v-if="isConditionMet(item.condition)" :help="formErrors[item.key]" :validate-status="formErrors[item.key] ? 'error' : ''">
          <!-- 下拉 -->
          <a-select
            v-if="item.type === 'select' && item.valid.select.length > 4"
            v-model:value="form[item.key]"
            :placeholder="`请选择${item.nameZh}`"
          >
            <a-select-option v-for="t in item.valid.select" :key="t.value" :value="t.value">
              {{ t.label }}
            </a-select-option>
          </a-select>
          <!-- checkbox -->
          <a-radio-group v-else-if="item.type === 'select' && item.valid.select.length <= 4" v-model:value="form[item.key]" :name="item.key">
            <a-radio v-for="t in item.valid.select" :key="t.value" :value="t.value">{{ t.label }}</a-radio>
          </a-radio-group>
          <!-- 输入 -->
          <a-input
            v-else-if="item.type === 'string'"
            v-model:value="form[item.key]"
            :placeholder="`请输入${item.nameZh}`"
            @mouseenter="showTooltip(item)"
            @mouseleave="hideTooltip"
          />
          <!-- 数值 -->
          <a-input-number
            v-else-if="item.type === 'int'"
            v-model:value="form[item.key]"
            style="width: 100%"
            :placeholder="`请输入${item.nameZh}`"
            @mouseenter="showTooltip(item)"
            @mouseleave="hideTooltip"
          />
          <!-- 提示框 -->
          <div v-if="showDescription && tooltipItem === item" class="tooltip">
            {{ item.descriptionZh }}
          </div>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup>
  import { reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';

  let rules = ref({});
  let form = reactive({});
  const formRef = ref();
  let formOptions = ref([]);

  // 用于存放每个表单项的错误信息
  const formErrors = reactive({});

  // 控制提示显示与隐藏
  const showDescription = ref(false);
  const tooltipItem = ref(null);

  // 校验数字输入的值
  function validateValue(item) {
    const value = form[item.key];
    if (item.valid) {
      if (item.valid.min !== undefined && value < item.valid.min) {
        formErrors[item.key] = `${item.nameZh}不能小于${item.valid.min}`;
        message.error(formErrors[item.key]);
      } else if (item.valid.max !== undefined && value > item.valid.max) {
        formErrors[item.key] = `${item.nameZh}不能大于${item.valid.max}`;
        message.error(formErrors[item.key]);
      } else {
        // 清除错误信息
        formErrors[item.key] = '';
      }
    }
  }

  // 显示提示框
  function showTooltip(item) {
    if (item.descriptionZh) {
      showDescription.value = true;
      tooltipItem.value = item;
    }
  }

  // 隐藏提示框
  function hideTooltip() {
    showDescription.value = false;
    tooltipItem.value = null;
  }

  // 设置表单选项并更新规则
  function setOptions(list) {
    rules.value = {};
    let formData = {};
    for (let item of list) {
      // 处理 required 验证
      if (item.attribute === 'required') {
        let message = '';
        if (item.type === 'string' || item.type === 'int') {
          message = '请填写';
        } else {
          message = '请选择';
        }

        if (!rules.value[item.key]) {
          rules.value[item.key] = [];
        }

        rules.value[item.key].push({
          required: true,
          message: message + item.nameZh
        });
      }

      // 自定义验证
      if (item.valid) {
        if (!rules.value[item.key]) {
          rules.value[item.key] = [];
        }

        rules.value[item.key].push({
          validator: (rule, value) => {
            formErrors[item.key] = ''; // 清空错误信息

            // 校验最小值和最大值
            if (item.valid.min !== undefined && value < item.valid.min) {
              formErrors[item.key] = `${item.nameZh}不能小于${item.valid.min}`;
              return Promise.reject(formErrors[item.key]);
            }
            if (item.valid.max !== undefined && value > item.valid.max) {
              formErrors[item.key] = `${item.nameZh}不能大于${item.valid.max}`;
              return Promise.reject(formErrors[item.key]);
            }

            return Promise.resolve();
          },
        });
      }
      formData[item.key] = undefined;
    }
    Object.assign(form, formData);
    formOptions.value = list;
  }

  // 点击确定，验证表单
  async function onSubmit() {
      await formRef.value.validateFields();
  }

  // 返回值
  function getChildFormData() {
    return form;
  }

  // 编辑的时候的赋值
  function setChildFormData(data) {
    Object.assign(form, data);
  }

  function isConditionMet(condition) {
    // 如果没有条件或字段，直接满足
    if (!condition || !condition.field) return true;

    // 解析 condition 中的 field 和 value
    const [mainField, ...restConditions] = condition.value.split(':');
    const fieldValue = form[condition.field];

    // 递归检查子条件（如果有的话）
    const checkSubConditions = (conditions) => {
      if (!conditions || conditions.length === 0) return true;

      const conditionStr = conditions[0];

      // 处理非条件 `!`
      const isNegated = conditionStr.startsWith('!');
      const conditionParts = isNegated ? conditionStr.slice(1).split('.') : conditionStr.split('.');

      const subConditionField = conditionParts[0];
      const subConditionValue = conditionParts[1];

      const subConditionFieldValue = form[subConditionField];

      // 如果是非条件，判断该条件是否不符合
      const conditionMet = subConditionFieldValue === subConditionValue;

      // 如果有 !，则取反
      if (isNegated ? conditionMet : !conditionMet) {
        return false;
      }

      // 递归检查后续子条件
      return checkSubConditions(conditions.slice(1));
    };

    // 检查主条件是否符合
    if (fieldValue !== mainField) return false;

    // 检查子条件（支持 | 或的情况）
    if (restConditions.length > 0) {
      // 分割子条件并处理每个子条件
      const subConditions = restConditions.join(':').split('|').map(subCondition => subCondition.split(':'));

      // 检查子条件中的每一个，如果有一个满足条件，就返回 true
      return subConditions.some(subCondition => checkSubConditions(subCondition));
    }

    return true;
  }

  watch(form, (newValue) => {
    for (let item of formOptions.value) {
      if (item.condition) {
        const link = item.condition.link;
        // 只需要判断当前有值，然后给他赋上去不就好了
        if (newValue[link]) {
          const valid = item.valid.select;
          const row = valid.find((m) => m.link === newValue[link]) || {};
          form[item.key] = row.value;
        }
      }
    }
  });

  defineExpose({
    setOptions,
    onSubmit,
    getChildFormData,
    setChildFormData,
  });
</script>

<style scoped>
  /* Tooltip 样式 */
  .tooltip {
    position: absolute;
    background-color: #f0f0f0;
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #ccc;
    font-size: 12px;
    max-width: 200px;
    z-index: 100;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  }

  input {
    position: relative;
  }
</style>
